package com.sec.android.app.myfiles.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import com.sec.android.app.myfiles.log.Log;

import java.util.List;

/**
 * Created by hyejung8.kim on 2017-07-07.
 */

public class AppIconUpdateBadgeSetter {
    private static final String LOG_TAG = "AppIconUpdateBadgeSetter";
    private static final String sLauncherClassName = "com.sec.android.app.myfiles.common.MainActivity";

    private static final String ACTION_BADGE_UPDATE_BROADCAST = "android.intent.action.BADGE_COUNT_UPDATE";
    private static final String ACTION_SEC_BADGE_UPDATE_BROADCAST = "com.sec.intent.action.BADGE_COUNT_UPDATE";

    private static class BadgeExtra {
        static final String COUNT = "badge_count";
        static final String PACKAGE = "badge_count_package_name";
        static final String CLASS = "badge_count_class_name";
    }

    public static void setBadge(Context context, int count) {
//        String sLauncherClassName = getLauncherClassName(context);
//        if (sLauncherClassName == null) {
//            Log.e(LOG_TAG, "setBadge sLauncherClassName is null");
//            return;
//        }

        Log.i(LOG_TAG, "HJ setBadge count : " + count);
        Intent intent = new Intent(ACTION_BADGE_UPDATE_BROADCAST);
        intent.putExtra(BadgeExtra.COUNT, count);
        intent.putExtra(BadgeExtra.PACKAGE, context.getPackageName());
        intent.putExtra(BadgeExtra.CLASS, sLauncherClassName);
        context.sendBroadcast(intent);

        Intent secIntent = new Intent(ACTION_SEC_BADGE_UPDATE_BROADCAST);
        secIntent.putExtra(BadgeExtra.COUNT, count);
        secIntent.putExtra(BadgeExtra.PACKAGE, context.getPackageName());
        secIntent.putExtra(BadgeExtra.CLASS, sLauncherClassName);
        context.sendBroadcast(secIntent);
        Log.i(LOG_TAG, "HJ setBadge count : " + count);
    }

    public static void clearBadge(Context context) {
        Log.i(LOG_TAG, "HJ clearBadge");
        setBadge(context, 0);
    }

    private static String getLauncherClassName(Context context) {
        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                Log.d(LOG_TAG, "getLauncherClassName : " + className);
                return className;
            }
        }
        return null;
    }
}
